#include "client.h"

int main(int argc, char* argv[])
{
    ARGS_CHECK(argc, 3);
    thread_t thread;
    threadInit(&thread);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    memcpy(&thread.port,&addr.sin_port,sizeof(thread.port));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    memcpy(&thread.IP,&addr.sin_addr.s_addr,sizeof(uint32_t));
    int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret, -1, "connect");

    //告诉服务端处理短命令
    train_t train;
    bzero(&train,sizeof(train));
    train.tag = LOGIN;
    send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);
    
    //登录
    char usrname[128] = {0};
    char password[128] = {0};
    while(1){
        getMsg(usrname,password);
        if(login(sockfd,usrname,password) == 0){
            break;
        }
        printf("wrong password, try again.\n");
    }
    printf("login success.\n");
    memcpy(thread.usrname,usrname,strlen(usrname) + 1);

    //接收token
    recvn(sockfd,&train,sizeof(train));
    memcpy(thread.token,train.data,train.length);

    //业务
    char buf[1024];
    while(1){
        bzero(buf,sizeof(buf));
        bzero(&train,sizeof(train));
        printf(">");
        fflush(stdout);
        int ret = read(STDIN_FILENO,buf,sizeof(buf));
        LOG_ERROR_CHECK(ret,-1,"read STDIN_FILENO");
        if(buf[0] == '\n'){
            continue;
        }
        buf[strcspn(buf,"\n")] = '\0';
        ret = commandToken(buf,&train);
        if(ret == -1){
            printf("Error, try again.\n");
            continue;
        }
        int flag = 0;
        switch(train.tag){
        case CD:
        case LS:
        case PWD:
        case MKDIR:
        case RMDIR:
        case REMOVE:
            send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);
            break;
        case PUTS:
        case GETS:
            thread.tag = train.tag;
            memcpy(thread.path,train.data,train.length);
            makethread(&thread);
            break;
        case QUIT:
            flag = 2;
            break;
        default:
            flag = 1;
        }
        if(flag == 1){
            printf("ERROR, try again.\n");
            continue;
        }else if(flag == 2){
            send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);
            break;
        }
        if(train.tag == LS){
            recvLS(sockfd);
        }else if(train.tag == PWD){
            recvPWD(sockfd);
        }
    }
    return 0;
}
